package com.ruoyi.common.core.page;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.CaseFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * @author 697
 * @since 2022/2/16 9:52
 */
@Data
@ApiModel(value = "分页请求对象", description = "分页请求对象")
public class PageQuery2 implements Serializable {

    private static final long serialVersionUID = -8632499088114943055L;

    @ApiModelProperty(value = "当前页数")
    private Long pageCurrent;

    @ApiModelProperty(value = "每页大小")
    private Long pageSize;

    @ApiModelProperty(value = "排序字段")
    private String sortColumn;

    @ApiModelProperty(value = "排序规则")
    private Boolean sortAsc = true;

    /**
     * 构建分页对象
     *
     * @param <T> 类型
     * @return 分页模型
     */
    public <T> Page<T> buildPage() {
        PageQuery2 params = this;
        Page<T> page = new Page<>();
        Optional.ofNullable(params.getPageCurrent()).ifPresent(page::setCurrent);
        Optional.ofNullable(params.getPageSize()).ifPresent(page::setSize);
        if (!StringUtils.isBlank(params.getSortColumn())) {
            List<OrderItem> orders = new ArrayList<>();
            // 简单的 驼峰 转 下划线
            String column = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, params.getSortColumn());
            orders.add(params.getSortAsc() ? OrderItem.asc(column) : OrderItem.desc(column));
            page.setOrders(orders);
        }
        return page;
    }

    public <T, E> Page<T> convert(Page<E> page, Function<List<E>, List<T>> etFunction) {
        Page<T> objectPage = this.buildPage();
        objectPage.setTotal(page.getTotal());
        objectPage.setRecords(etFunction.apply(page.getRecords()));
        return objectPage;
    }
}
